package com.codebox.common.util.glide;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.codebox.common.R;


/**
 * @author 李立
 * @date 2018/12/6
 *
 * glide工具类
 */
public class GlideUtil {


    /**
     * 设置前景
     */
    public static <T> void load(Context context, T t, final ImageView imageView, int errorId) {
        load(context, t, imageView, errorId, null);

    }

    /**
     * 设置前景
     * //
     */
    public static <T> void load(Context context, T t, final ImageView imageView, int errorId, RequestListener<Drawable> listener) {
        RequestOptions options = new RequestOptions()
                .placeholder(errorId).dontAnimate()
                .format(DecodeFormat.PREFER_RGB_565)
                .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
                .error(errorId);


        String img = null;
        if (t instanceof String) {
            img = (String) t;
        }
        if (!isValidContextForGlide(context)) {
            return;
        }

        try {
            Glide.with(context)
                    .load(img == null ? t : img)
                    .apply(options)
                    .listener(
                            new RequestListener<Drawable>() {
                                @Override
                                public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                                    return false;
                                }

                                @Override
                                public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {

                                    imageView.setImageDrawable(resource);
                                    return false;
                                }
                            })
                    .into(imageView);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static boolean isValidContextForGlide(final Context context) {
        if (context == null) {
            return false;
        }
        if (context instanceof Activity) {
            final Activity activity = (Activity) context;
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {
                if (activity.isDestroyed()) {
                    return false;
                }
            }

            if (activity.isFinishing()) {
                return false;
            }
        }
        return true;
    }

    /**
     * 设置前景
     */
    public static <T> void loadCropCircle(Context context, T t, ImageView imageView, int errorId) {
        RequestOptions options = new RequestOptions()
                .placeholder(errorId)
                .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                .error(errorId).dontAnimate().circleCrop();

        if (!(context instanceof Application)) {
            context = context.getApplicationContext();
        }

        if (t instanceof String) {
            String img = (String) t;

            Glide.with(context)
                    .load(img)
                    .apply(options)
                    .into(imageView);
        } else {
            Glide.with(context)
                    .load(t)
                    .apply(options)
                    .into(imageView);
        }
    }


    /**
     * 设置前景
     */
    public static <T> void loadARGB(Context context, final T t, final ImageView imageView, int errorId) {
        RequestOptions options = new RequestOptions()
                .format(DecodeFormat.PREFER_ARGB_8888)
//                .dontTransform()
                .placeholder(errorId)

                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .error(errorId);

        if (!(context instanceof Application)) {
            context = context.getApplicationContext();
        }
        final Context finalContext = context;
        Glide.with(context).asBitmap()
                .load(t)
                .apply(options)
                .into(new SimpleTarget<Bitmap>(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) {

                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        int imageHeight = resource.getHeight();
                        if (imageHeight > 4096) {
                            imageHeight = 4096;
                            ViewGroup.LayoutParams para = imageView.getLayoutParams();
                            if (para == null) {
                                para = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, imageHeight);
                            }
                            para.width = ViewGroup.LayoutParams.MATCH_PARENT;
                            para.height = imageHeight;
                            imageView.setLayoutParams(para);
                            Glide.with(finalContext)
                                    .load(t)
                                    .into(imageView);


                        } else {
                            Glide.with(finalContext)
                                    .load(t)
                                    .into(imageView);
                        }
                    }
                });


    }


    /**
     * 设置前景(圆角)
     */
    public static <T> void loadRoundedCorners(Context context, T t, ImageView imageView, int errorId) {

        RequestOptions options = new RequestOptions()
                .placeholder(errorId)
                .centerCrop()
                .bitmapTransform(new RoundedCornersTransformation(10, 0))
//                .bitmapTransform(new RoundedCornersTransformation(45, 10,
//                RoundedCornersTransformation.CornerType.ALL))
                .diskCacheStrategy(DiskCacheStrategy.ALL)
//                .bitmapTransform(new RoundedCornersTransformation( 30, 0, RoundedCornersTransformation.CornerType.ALL)).crossFade(1000)
                .error(errorId);
        if (!(context instanceof Application)) {
            context = context.getApplicationContext();
        }
        Glide.with(context).asBitmap()
                .load(t)
                .apply(options)

                .into(imageView);

    }

    /**
     * 设置前景(圆角)
     */
    public static <T> void loadRoundedCorners(Context context, T t, ImageView imageView, int radius, int errorId) {

        RequestOptions options = new RequestOptions()
                .placeholder(errorId)
                .centerCrop()
                .bitmapTransform(new RoundedCornersTransformation(radius, 0))
//                .bitmapTransform(new RoundedCornersTransformation(45, 10,
//                RoundedCornersTransformation.CornerType.ALL))
                .diskCacheStrategy(DiskCacheStrategy.ALL)
//                .bitmapTransform(new RoundedCornersTransformation( 30, 0, RoundedCornersTransformation.CornerType.ALL)).crossFade(1000)
                .error(errorId);
        if (!(context instanceof Application)) {
            context = context.getApplicationContext();
        }
        Glide.with(context).asBitmap()
                .load(t)
                .apply(options)

                .into(imageView);

    }


    /**
     * 设置前景(圆角)
     */
    public static <T> void loadBannerImage(Context context, T t, ImageView imageView, int errorId, int width, int height) {

        RequestOptions options = new RequestOptions()
                .placeholder(errorId)
                .centerCrop()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .override(width, height)
                .error(errorId);
        if (!(context instanceof Application)) {
            context = context.getApplicationContext();
        }
        Glide.with(context).asBitmap()
                .load(t)
                .apply(options)

                .into(imageView);
    }


    /**
     * 设置前景
     */
    public static <T> void load(Context context, String url, int errorId, ImageView imageView) {
        RequestOptions options = new RequestOptions()
                .placeholder(errorId)
                .error(errorId).centerCrop();
        if (!(context instanceof Application)) {
            context = context.getApplicationContext();
        }

        Glide.with(context)
                .load(url)
                .apply(options)
                .into(imageView);
    }


    public static <T> void load(Context context, T t, ImageView imageView, RequestListener<Drawable> listener) {
        load(context, t, imageView, R.mipmap.ic_launcher, listener);
    }

    public static <T> void load(Context context, T t, ImageView imageView) {
        load(context, t, imageView, R.mipmap.ic_launcher);
    }


    public static <T> void loadAvatar(Context context, T t, ImageView imageView) {

        loadCropCircle(context, t, imageView, R.mipmap.ic_launcher_round);
    }


    public static <T> void loadNetWokrImage(Context context, T t, String url, ImageView imageView) {
        load(context, url, R.mipmap.ic_launcher, imageView);
    }

    /**
     * 直接将ImageView 加载成圆形
     */
    public static <T> void loadRound(Context context, T t, ImageView imageView) {

        RequestOptions requestOptions = RequestOptions.circleCropTransform().
                placeholder(R.mipmap.ic_launcher_round).error(R.mipmap.ic_launcher_round);

        if (!(context instanceof Application)) {
            context = context.getApplicationContext();
        }
        Glide.with(context).load(t).apply(requestOptions).into(imageView);
    }

}
